<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML
><HEAD
><TITLE
>Writing A Procedural Language Handler</TITLE
><META
NAME="GENERATOR"
CONTENT="Modular DocBook HTML Stylesheet Version 1.79"><LINK
REV="MADE"
HREF="mailto:pgsql-docs@postgresql.org"><LINK
REL="HOME"
TITLE="PostgreSQL 9.1.2 Documentation"
HREF="index.html"><LINK
REL="UP"
TITLE="Internals"
HREF="internals.html"><LINK
REL="PREVIOUS"
TITLE="For the Programmer"
HREF="nls-programmer.html"><LINK
REL="NEXT"
TITLE="Writing A Foreign Data Wrapper"
HREF="fdwhandler.html"><LINK
REL="STYLESHEET"
TYPE="text/css"
HREF="stylesheet.css"><META
HTTP-EQUIV="Content-Type"
CONTENT="text/html; charset=ISO-8859-1"><META
NAME="creation"
CONTENT="2011-12-01T22:07:59"></HEAD
><BODY
CLASS="CHAPTER"
><DIV
CLASS="NAVHEADER"
><TABLE
SUMMARY="Header navigation table"
WIDTH="100%"
BORDER="0"
CELLPADDING="0"
CELLSPACING="0"
><TR
><TH
COLSPAN="5"
ALIGN="center"
VALIGN="bottom"
><A
HREF="index.html"
>PostgreSQL 9.1.2 Documentation</A
></TH
></TR
><TR
><TD
WIDTH="10%"
ALIGN="left"
VALIGN="top"
><A
TITLE="For the Programmer"
HREF="nls-programmer.html"
ACCESSKEY="P"
>Prev</A
></TD
><TD
WIDTH="10%"
ALIGN="left"
VALIGN="top"
><A
HREF="internals.html"
ACCESSKEY="U"
>Up</A
></TD
><TD
WIDTH="60%"
ALIGN="center"
VALIGN="bottom"
></TD
><TD
WIDTH="20%"
ALIGN="right"
VALIGN="top"
><A
TITLE="Writing A Foreign Data Wrapper"
HREF="fdwhandler.html"
ACCESSKEY="N"
>Next</A
></TD
></TR
></TABLE
><HR
ALIGN="LEFT"
WIDTH="100%"></DIV
><DIV
CLASS="CHAPTER"
><H1
><A
NAME="PLHANDLER"
></A
>Chapter 49. Writing A Procedural Language Handler</H1
><P
>    All calls to functions that are written in a language other than
    the current <SPAN
CLASS="QUOTE"
>"version 1"</SPAN
> interface for compiled
    languages (this includes functions in user-defined procedural languages,
    functions written in SQL, and functions using the version 0 compiled
    language interface) go through a <I
CLASS="FIRSTTERM"
>call handler</I
>
    function for the specific language.  It is the responsibility of
    the call handler to execute the function in a meaningful way, such
    as by interpreting the supplied source text.  This chapter outlines
    how a new procedural language's call handler can be written.
   </P
><P
>    The call handler for a procedural language is a
    <SPAN
CLASS="QUOTE"
>"normal"</SPAN
> function that must be written in a compiled
    language such as C, using the version-1 interface, and registered
    with <SPAN
CLASS="PRODUCTNAME"
>PostgreSQL</SPAN
> as taking no arguments
    and returning the type <TT
CLASS="TYPE"
>language_handler</TT
>.  This
    special pseudotype identifies the function as a call handler and
    prevents it from being called directly in SQL commands.
    For more details on C language calling conventions and dynamic loading,
    see <A
HREF="xfunc-c.html"
>Section 35.9</A
>.
   </P
><P
>    The call handler is called in the same way as any other function:
    It receives a pointer to a
    <TT
CLASS="STRUCTNAME"
>FunctionCallInfoData</TT
> <TT
CLASS="TYPE"
>struct</TT
> containing
    argument values and information about the called function, and it
    is expected to return a <TT
CLASS="TYPE"
>Datum</TT
> result (and possibly
    set the <TT
CLASS="STRUCTFIELD"
>isnull</TT
> field of the
    <TT
CLASS="STRUCTNAME"
>FunctionCallInfoData</TT
> structure, if it wishes
    to return an SQL null result).  The difference between a call
    handler and an ordinary callee function is that the
    <TT
CLASS="STRUCTFIELD"
>flinfo-&gt;fn_oid</TT
> field of the
    <TT
CLASS="STRUCTNAME"
>FunctionCallInfoData</TT
> structure will contain
    the OID of the actual function to be called, not of the call
    handler itself.  The call handler must use this field to determine
    which function to execute.  Also, the passed argument list has
    been set up according to the declaration of the target function,
    not of the call handler.
   </P
><P
>    It's up to the call handler to fetch the entry of the function from the
    <CODE
CLASS="CLASSNAME"
>pg_proc</CODE
> system catalog and to analyze the argument
    and return types of the called function. The <TT
CLASS="LITERAL"
>AS</TT
> clause from the
    <TT
CLASS="COMMAND"
>CREATE FUNCTION</TT
> command for the function will be found
    in the <TT
CLASS="LITERAL"
>prosrc</TT
> column of the
    <CODE
CLASS="CLASSNAME"
>pg_proc</CODE
> row. This is commonly source
    text in the procedural language, but in theory it could be something else,
    such as a path name to a file, or anything else that tells the call handler
    what to do in detail.
   </P
><P
>    Often, the same function is called many times per SQL statement.
    A call handler can avoid repeated lookups of information about the
    called function by using the
    <TT
CLASS="STRUCTFIELD"
>flinfo-&gt;fn_extra</TT
> field.  This will
    initially be <TT
CLASS="SYMBOL"
>NULL</TT
>, but can be set by the call handler to point at
    information about the called function.  On subsequent calls, if
    <TT
CLASS="STRUCTFIELD"
>flinfo-&gt;fn_extra</TT
> is already non-<TT
CLASS="SYMBOL"
>NULL</TT
>
    then it can be used and the information lookup step skipped.  The
    call handler must make sure that
    <TT
CLASS="STRUCTFIELD"
>flinfo-&gt;fn_extra</TT
> is made to point at
    memory that will live at least until the end of the current query,
    since an <TT
CLASS="STRUCTNAME"
>FmgrInfo</TT
> data structure could be
    kept that long.  One way to do this is to allocate the extra data
    in the memory context specified by
    <TT
CLASS="STRUCTFIELD"
>flinfo-&gt;fn_mcxt</TT
>; such data will
    normally have the same lifespan as the
    <TT
CLASS="STRUCTNAME"
>FmgrInfo</TT
> itself.  But the handler could
    also choose to use a longer-lived memory context so that it can cache
    function definition information across queries.
   </P
><P
>    When a procedural-language function is invoked as a trigger, no arguments
    are passed in the usual way, but the
    <TT
CLASS="STRUCTNAME"
>FunctionCallInfoData</TT
>'s
    <TT
CLASS="STRUCTFIELD"
>context</TT
> field points at a
    <TT
CLASS="STRUCTNAME"
>TriggerData</TT
> structure, rather than being <TT
CLASS="SYMBOL"
>NULL</TT
>
    as it is in a plain function call.  A language handler should
    provide mechanisms for procedural-language functions to get at the trigger
    information.
   </P
><P
>    This is a template for a procedural-language handler written in C:
</P><PRE
CLASS="PROGRAMLISTING"
>#include "postgres.h"
#include "executor/spi.h"
#include "commands/trigger.h"
#include "fmgr.h"
#include "access/heapam.h"
#include "utils/syscache.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"

#ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif

PG_FUNCTION_INFO_V1(plsample_call_handler);

Datum
plsample_call_handler(PG_FUNCTION_ARGS)
{
    Datum          retval;

    if (CALLED_AS_TRIGGER(fcinfo))
    {
        /*
         * Called as a trigger procedure
         */
        TriggerData    *trigdata = (TriggerData *) fcinfo-&gt;context;

        retval = ...
    }
    else
    {
        /*
         * Called as a function
         */

        retval = ...
    }

    return retval;
}</PRE
><P>
    Only a few thousand lines of code have to be added instead of the
    dots to complete the call handler.
   </P
><P
>    After having compiled the handler function into a loadable module
    (see <A
HREF="xfunc-c.html#DFUNC"
>Section 35.9.6</A
>), the following commands then
    register the sample procedural language:
</P><PRE
CLASS="PROGRAMLISTING"
>CREATE FUNCTION plsample_call_handler() RETURNS language_handler
    AS '<TT
CLASS="REPLACEABLE"
><I
>filename</I
></TT
>'
    LANGUAGE C;
CREATE LANGUAGE plsample
    HANDLER plsample_call_handler;</PRE
><P>
   </P
><P
>    Although providing a call handler is sufficient to create a minimal
    procedural language, there are two other functions that can optionally
    be provided to make the language more convenient to use.  These
    are a <I
CLASS="FIRSTTERM"
>validator</I
> and an
    <I
CLASS="FIRSTTERM"
>inline handler</I
>.  A validator can be provided
    to allow language-specific checking to be done during
    <A
HREF="sql-createfunction.html"
>CREATE FUNCTION</A
>.
    An inline handler can be provided to allow the language to support
    anonymous code blocks executed via the <A
HREF="sql-do.html"
>DO</A
> command.
   </P
><P
>    If a validator is provided by a procedural language, it
    must be declared as a function taking a single parameter of type
    <TT
CLASS="TYPE"
>oid</TT
>.  The validator's result is ignored, so it is customarily
    declared to return <TT
CLASS="TYPE"
>void</TT
>.  The validator will be called at
    the end of a <TT
CLASS="COMMAND"
>CREATE FUNCTION</TT
> command that has created
    or updated a function written in the procedural language.
    The passed-in OID is the OID of the function's <CODE
CLASS="CLASSNAME"
>pg_proc</CODE
>
    row.  The validator must fetch this row in the usual way, and do
    whatever checking is appropriate.  Typical checks include verifying
    that the function's argument and result types are supported by the
    language, and that the function's body is syntactically correct
    in the language.  If the validator finds the function to be okay,
    it should just return.  If it finds an error, it should report that
    via the normal <CODE
CLASS="FUNCTION"
>ereport()</CODE
> error reporting mechanism.
    Throwing an error will force a transaction rollback and thus prevent
    the incorrect function definition from being committed.
   </P
><P
>    Validator functions should typically honor the <A
HREF="runtime-config-client.html#GUC-CHECK-FUNCTION-BODIES"
>check_function_bodies</A
> parameter: if it is turned off then
    any expensive or context-sensitive checking should be skipped.
    In particular, this parameter is turned off by <SPAN
CLASS="APPLICATION"
>pg_dump</SPAN
>
    so that it can load procedural language functions without worrying
    about possible dependencies of the function bodies on other database
    objects.  (Because of this requirement, the call handler should avoid
    assuming that the validator has fully checked the function.  The point
    of having a validator is not to let the call handler omit checks, but
    to notify the user immediately if there are obvious errors in a
    <TT
CLASS="COMMAND"
>CREATE FUNCTION</TT
> command.)
   </P
><P
>    If an inline handler is provided by a procedural language, it
    must be declared as a function taking a single parameter of type
    <TT
CLASS="TYPE"
>internal</TT
>.  The inline handler's result is ignored, so it is
    customarily declared to return <TT
CLASS="TYPE"
>void</TT
>.  The inline handler
    will be called when a <TT
CLASS="COMMAND"
>DO</TT
> statement is executed specifying
    the procedural language.  The parameter actually passed is a pointer
    to an <TT
CLASS="STRUCTNAME"
>InlineCodeBlock</TT
> struct, which contains information
    about the <TT
CLASS="COMMAND"
>DO</TT
> statement's parameters, in particular the
    text of the anonymous code block to be executed.  The inline handler
    should execute this code and return.
   </P
><P
>    It's recommended that you wrap all these function declarations,
    as well as the <TT
CLASS="COMMAND"
>CREATE LANGUAGE</TT
> command itself, into
    an <I
CLASS="FIRSTTERM"
>extension</I
> so that a simple <TT
CLASS="COMMAND"
>CREATE EXTENSION</TT
>
    command is sufficient to install the language.  See
    <A
HREF="extend-extensions.html"
>Section 35.15</A
> for information about writing
    extensions.
   </P
><P
>    The procedural languages included in the standard distribution
    are good references when trying to write your own language handler.
    Look into the <TT
CLASS="FILENAME"
>src/pl</TT
> subdirectory of the source tree.
    The <A
HREF="sql-createlanguage.html"
>CREATE LANGUAGE</A
>
    reference page also has some useful details.
   </P
></DIV
><DIV
CLASS="NAVFOOTER"
><HR
ALIGN="LEFT"
WIDTH="100%"><TABLE
SUMMARY="Footer navigation table"
WIDTH="100%"
BORDER="0"
CELLPADDING="0"
CELLSPACING="0"
><TR
><TD
WIDTH="33%"
ALIGN="left"
VALIGN="top"
><A
HREF="nls-programmer.html"
ACCESSKEY="P"
>Prev</A
></TD
><TD
WIDTH="34%"
ALIGN="center"
VALIGN="top"
><A
HREF="index.html"
ACCESSKEY="H"
>Home</A
></TD
><TD
WIDTH="33%"
ALIGN="right"
VALIGN="top"
><A
HREF="fdwhandler.html"
ACCESSKEY="N"
>Next</A
></TD
></TR
><TR
><TD
WIDTH="33%"
ALIGN="left"
VALIGN="top"
>For the Programmer</TD
><TD
WIDTH="34%"
ALIGN="center"
VALIGN="top"
><A
HREF="internals.html"
ACCESSKEY="U"
>Up</A
></TD
><TD
WIDTH="33%"
ALIGN="right"
VALIGN="top"
>Writing A Foreign Data Wrapper</TD
></TR
></TABLE
></DIV
></BODY
></HTML
>